<template>
  <div>
    <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents">
      <template #id="{ row }">
        <vxe-input v-model="row.id" />
      </template>
      <template #state="{ row }">
        <!-- <vxe-input v-model="row.state" /> -->
        <el-tag type="primary" v-if="row.state == 0">{{ formatStatus(row.state) }}</el-tag>
        <el-tag type="success" v-if="row.state == 1">{{ formatStatus(row.state) }}</el-tag>
        <el-tag type="info" v-if="row.state == 2">{{ formatStatus(row.state) }}</el-tag>
        <el-tag type="warning" v-if="row.state == 3">{{ formatStatus(row.state) }}</el-tag>
      </template>
      <template #user_id="{ row }">
        <vxe-input v-model="row.user_id" />
      </template>
      <template #user_owner_id="{ row }">
        <vxe-input v-model="row.user_owner_id" />
      </template>
      <template #house_id="{ row }">
        <vxe-input v-model="row.house_id" />
      </template>写
      <template #rmb="{ row }">
        <vxe-input v-model="row.rmb" />
      </template>
      <template #start_time="{ row }">
        <vxe-input v-model="row.start_time" />
      </template>
      <template #end_time="{ row }">
        <vxe-input v-model="row.end_time" />
      </template>
      <template #operate="{ row }">
        <vxe-button v-if="isUser" status="danger" content="退单" @click="tuidan(row)"></vxe-button>
        <vxe-button
          v-if="isSuperManager"
          status="danger"
          content="删除"
          @click="deleteOrders(row)"
        ></vxe-button>
      </template>
      <template #pager>
        <!--使用 pager 插槽-->
        <vxe-pager
          :layouts="[
            'Sizes',
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'FullJump',
            'Total',
          ]"
          v-model:current-page="tablePage.currentPage"
          v-model:page-size="tablePage.pageSize"
          :total="tablePage.total"
          @page-change="handlePageChange"
        />
      </template>
    </vxe-grid>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue'
  import VXETable from 'vxe-table'
  import { RoleEnum } from '/@/enums/roleEnum'
  import { createLocalStorage } from '/@/utils/cache'
  import { LOCALE_KEY } from '/@/enums/cacheEnum'
  import { getOrderList, insertOrder, updateOrder, deleteOrder } from '/@/api/order/order.ts'
  import { ElMessage } from 'element-plus'

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })
  const defaultCulums = reactive([
    { type: 'checkbox', width: 50 },
    { type: 'seq', width: 60 },
    { field: 'id', title: '编号', slots: { edit: 'id' } },
    { field: 'state', title: '订单状态', slots: { default: 'state', edit: 'state' } },
    { field: 'user_id', title: '用户编号', slots: { edit: 'user_id' } },
    { field: 'user_owner_id', title: '房主编号', slots: { edit: 'user_owner_id' } },
    { field: 'house_id', title: '房间编号', slots: { edit: 'house_id' } },
    { field: 'rmb', title: '价格', slots: { edit: 'rmb' } },
    { field: 'start_time', title: '起始时间', slots: { edit: 'start_time' } },
    { field: 'end_time', title: '结束时间', slots: { edit: 'end_time' } },

    { title: '操作', width: 100, slots: { default: 'operate' } },
  ])
  const validRules = ref({
    state: [{ required: true, message: '请输入state' }],
    user_id: [{ required: true, message: '请输入user_id' }],
    rmb: [{ required: true, message: '请输入rmb' }],
    start_time: [{ required: true, message: '请输入start_time' }],
    end_time: [{ required: true, message: '请输入end_times' }],
  })
  const xGrid = ref()
  let gridOptions = reactive({
    border: true,
    keepSource: true,
    id: 'toolbar_demo_1',
    height: 530,
    editRules: validRules,
    printConfig: {},
    importConfig: {},
    exportConfig: {},
    columnConfig: {
      resizable: true,
    },
    customConfig: {
      storage: true,
    },

    columns: defaultCulums,
    toolbarConfig: {
      tools: [{ code: 'myPrint', name: '自定义打印' }],
      import: true,
      export: true,
      print: true,
      zoom: true,
      custom: true,
    },
    data: [
      {
        id: 367,
        uid: '15',
        name: '15',
        password: '15',
        type: 2,
        image: '15',
        rmb: 15,
        create_time: '2023-12-31 23:10:38',
      },
      {
        id: 368,
        uid: '16',
        name: '16',
        password: '16',
        type: 2,
        image: '16',
        rmb: 16,
        create_time: '2023-12-31 23:10:38',
      },
    ],
  })
  const ls = createLocalStorage()
  const userInfo = ls.get(LOCALE_KEY + 'bb_user_info')
  const isUser = userInfo.roles.find((item) => item.value == RoleEnum.User)
  const isSuperManager = userInfo.roles.find((item) => item.value == RoleEnum.SuperManager)
  if (userInfo.roles.find((item) => item.value !== RoleEnum.User)) {
    gridOptions.toolbarConfig.buttons = [
      { code: 'mySave', name: '保存', status: 'success' },
      { code: 'myExport', name: '导出数据', type: 'text', status: 'warning' },
    ]
    gridOptions.editConfig = {
      trigger: 'click',
      mode: 'row',
      showStatus: true,
    }
  }

  const formatStatus = (value) => {
    if (value == 0) {
      return '未使用'
    }
    if (value == 2) {
      return '已使用'
    }
    if (value == 3) {
      return '已退单'
    }
    if (value == 1) {
      return '使用中'
    }
  }
  const gridEvents = {
    async toolbarButtonClick({ code }) {
      const $grid = xGrid.value
      if ($grid) {
        switch (code) {
          case 'myInsert': {
            $grid.insert({})
            break
          }
          case 'myDelete': {
            $grid.removeCheckboxRow()
            break
          }
          case 'mySave': {
            const $table = xGrid.value
            if ($table) {
              const errMap = await $table.validate()
              if (errMap) {
                VXETable.modal.message({ status: 'error', message: '校验不通过！' })
                return
              } else {
                VXETable.modal.message({ status: 'success', message: '校验成功！' })
              }
            }
            const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
            const promise = []
            if (insertRecords.length > 0) {
              const promise1 = insertOrder(insertRecords).then((res) => {})
              promise.push(promise1)
            }
            if (removeRecords.length > 0) {
              const promise2 = deleteOrder(removeRecords).then((res) => {})
              promise.push(promise2)
            }
            if (updateRecords.length > 0) {
              const promise3 = updateOrder(updateRecords).then((res) => {})
              promise.push(promise3)
            }

            Promise.allSettled(promise).then(() => {
              getData()
              VXETable.modal.message({
                content: `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`,
                status: 'success',
              })
            })
            break
          }
          case 'myExport': {
            $grid.exportData({
              type: 'csv',
            })
            break
          }
        }
      }
    },
    toolbarToolClick({ code }) {
      const $grid = xGrid.value
      if ($grid) {
        switch (code) {
          case 'myPrint': {
            $grid.print()
            break
          }
        }
      }
    },
  }

  onMounted(() => {
    getData()
  })

  const getData = () => {
    const data = {
      page: 0,
    }
    getOrderList(data).then((res) => {
      const data1 = res.msg
      gridOptions.data = data1
    })
  }

  const handlePageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
  }

  const validEvent = async () => {
    const $table = xGrid.value
    if ($table) {
      const errMap = await $table.validate()
      if (errMap) {
        VXETable.modal.message({ status: 'error', message: '校验不通过！' })
      } else {
        VXETable.modal.message({ status: 'success', message: '校验成功！' })
      }
    }
  }

  const tuidan = (row) => {
    console.log(row)
    updateOrder([row]).then((res) => {
      if (res.state) {
        ElMessage({
          message: '退单成功',
          type: 'success',
        })
      } else {
        ElMessage({
          message: res?.msg,
          type: 'error',
        })
      }
      getData()
    })
  }

  const deleteOrders = (row) => {
    deleteOrder([row]).then((res) => {
      if (res.state) {
        ElMessage({
          message: '删除成功',
          type: 'error',
        })
      } else {
        ElMessage({
          message: res?.msg,
          type: 'error',
        })
      }
      getData()
    })
  }
</script>
<style lang="scss" scoped>
  :deep(.vxe-table--body-wrapper) {
    height: 500px !important;
  }
</style>